; detect.asm
; - detect internal 3K at $0400
; - original code by M.Kirchner / 2010

	.include "vicrom.inc"

	.export detect3k

VIC_BASE = $9000

	.segment "ZEROPAGE"

ptr:		.res 2
save:		.res 1

	.segment "CODE"
	
detect3k:	jmp @detect

; Test RAM at $0400..$07FF
; OUTPUT: Z = 1 .. RAM ok 
@check:		lda #0			; set ptr to $0400
			tay
			sta ptr
			lda #4
			sta ptr+1
			ldx #$0C
@check_00:	lda (ptr), y
			sta save
			lda #$55
			sta (ptr), y
			cmp (ptr), y
			bne @check_01
			asl
			sta (ptr), y
			cmp (ptr), y
			bne @check_01
			lda save
			sta (ptr), y
			iny
			bne @check_00
			inc ptr+1
			dex
			bne @check_00
@check_01:	rts

; Fill 8 pages from $0800 with increasing numbers
@init:		lda #$00		; set ptr to $0800
			tax
			tay
			sta ptr
			lda #$08
			sta ptr+1
@init_00:	txa
	.repeat 8
			sta (ptr), y
			iny
	.endrep
			bne @init_01
			inc ptr+1
@init_01:	inx
			bne @init_00
			rts

; Init video
@vic:		jsr CINT1
			ldx #$01
			ldy #$19
			ldy MACHINE
			cmp #$05
			beq @vic_00
			ldx #$06
			ldy #$1C
@vic_00:	lda #$9A
			sta VIC_BASE+5
			stx VIC_BASE
			sty VIC_BASE+2
			lda #$08
			sta VIC_BASE+15
			lda #$01
			ldy #$00
@vic_01:	sta $9400, y
			sta $9500, y
			sta $9600, y
			iny
			bne @vic_01
			rts

; Detect internal RAM at $0400..$07FF
; OUTPUT: Z = 1 .. RAM detected 
@detect:	jsr @check
			bne @detect_04
			jsr @init
			jsr @vic
			ldx #0
@detect_00:	lda pattern, x
			ldy #0
@detect_01:	sta $0400, y
			sta $0500, y
			sta $0600, y
			iny
			bne @detect_01
			sei
			ldy #$5E
@detect_02:	cpy VIC_BASE+4
			bne @detect_02
			ldy #$60
@detect_03:	cpy VIC_BASE+4
			bne @detect_03
	.repeat 4
			nop
	.endrep
			cmp $9200
			cli
			bne @detect_04
			inx
			cpx #16
			bne @detect_00
@detect_04:	php
			jsr CINT1
			plp
			rts
	
	.segment "RODATA"

pattern:	.byte 0, 1, 3, 7
			.byte 15, 31, 63, 127
			.byte 255, 254, 252, 248
			.byte 240, 224, 192, 128
